/**
   CheckCodeServiceImpl
 * Time:2018年5月25日
 */
package com.ssm.service.impl;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import com.ssm.service.CheckCodeService;

/**
 * @author 15199
 *
 */
@Service("checkCodeService")
public class CheckCodeServiceImpl implements CheckCodeService {

	/* (non-Javadoc)
	 * @see com.ssm.service.CheckCodeService#CreateCheckCode(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public void CreateCheckCode(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		response.setContentType("image/jpeg");
		 StringBuilder builderCode = new StringBuilder();
		//定义画布的宽高
		int width = 100;
		int height = 32;
		
		//创建画板
		BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);

		//获取画布
		Graphics g = image.getGraphics();
		
		//设置画笔的颜色
		g.setColor(Color.white);
		
		//填充画布
		g.fillRect(0, 0, width, height);
		
		
		//定义验证码的范围
		char words [] = "abcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
					   //012345
		//随机选取  创建随机对象
		Random rnd = new Random();
		
		//画4次
		for (int i = 0; i < 4; i++) {
			
			//设置画笔的颜色  随机一个颜色 rnd.nextInt(256) 随机一个0-255的int   
			g.setColor(new Color(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
			//设置字体
			g.setFont(new Font("宋体", Font.BOLD, 20));
			 char c =words [rnd .nextInt(words .length)];
	        builderCode.append(c);
			
			//画验证码
			g.drawString(c+"", i*15+20,20 );
		}
		
		// 画干扰点
		for (int i = 0; i < 50; i++) {
			g.setColor(new Color(rnd.nextInt(255), rnd.nextInt(255), rnd
					.nextInt(255)));
			g.drawOval(rnd.nextInt(width), rnd.nextInt(height), 1, 2);
		}
		
		for (int i = 0; i < 5; i++) {
			g.setColor(new Color(rnd.nextInt(255), rnd.nextInt(255), rnd.nextInt(255)));
			g.drawLine(rnd.nextInt(width), rnd.nextInt(height),
					rnd.nextInt(width), rnd.nextInt(height));
		}
		
		
		//将画布图片响应给页面  通过流
		OutputStream outputStream = response.getOutputStream();
		
		
		
		ImageIO.write(image, "jpeg", outputStream);
		 outputStream.flush();
		//6.保存到session中
	 	
		request.getSession().setAttribute("CheckCode", builderCode.toString());
		
	
		
	}

}
